package com.didispace.chapter36.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
 * @author: gx.wu
 * @create: 2023-04-24 10:59
 * @Description:
 */
@Slf4j
@Configuration
public class CallbackConfig {

    @Bean
    public RabbitTemplate createRabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate();
        rabbitTemplate.setConnectionFactory(connectionFactory);
        //设置开启Mandatory,才能触发回调函数,无论消息推送结果怎么样都强制调用回调函数
        rabbitTemplate.setMandatory(true);

        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                log.info("ConfirmCallback，correlationData：{}", correlationData);
                log.info("ConfirmCallback，ack：{}", ack);
                log.info("ConfirmCallback，cause：{}", cause);
            }
        });

        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                log.info("ReturnCallback，message：{}", message);
                log.info("ReturnCallback，replyCode：{}", replyCode);
                log.info("ReturnCallback，replyText：{}", replyText);
                log.info("ReturnCallback，exchange：{}", exchange);
                log.info("ReturnCallback，routingKey：{}", routingKey);
            }
        });
        return rabbitTemplate;
    }
}
